<?php




namespace App\Http\Controllers\Api\Divination;


use App\Http\Controllers\Api\BasicController;
use App\Models\Divination\Answer;
use App\Models\Divination\Divination;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\DB;
use Jiannei\Response\Laravel\Support\Facades\Response;

class DivinationController extends BasicController
{

    /**
     * @api {post} /div/quiz 预约&支付
     * @apiDescription
     * @apiHeader {String} Authorization='Bearer '
     */

    public function quiz(){
        $params=$this->data(['type','content','divination','price']);
        $params['uid']=$this->uid();
        $params['balance']=$params['price'];
        $result=Divination::create($params);
        return Response::success($result);
    }


    public function list(){
        $list=Divination::where(['status'=>1])->orderBy('id','desc')->paginate(10);
        return Response::success($list);
    }

    public function answer(){
        $params=$this->data(['div_id','answer','voice']);
        $params['teacher_id']=$this->uid();
        try {
            DB::beginTransaction();
            $amount=(new Answer())->run($this->uid(),$params['div_id']);
            $params['amount']=$amount;
            $result = Answer::create($params);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return Response::fail($e->getMessage());
        }

        return Response::success($result);
    }

    public function detail(){
        $id=$this->request->input('div_id');
        $div=Divination::with(['answers'=>function($query){
            $query->with(['user'=>function($query){
                $query->select(['id','name','avatar']);
            }]);
        },'user'=>function($query){
            $query->select(['id','name','avatar']);
        }])->find($id);
        $quizzer=Divination::where(['id'=>$id,'uid'=>$this->uid()])->first();
        if(empty($quizzer)){
            foreach ($div->answers as &$answer){
                if($answer->teacher_id != $this->uid())
                    unset($answer);
            }
        }
        return Response::success($div);
    }

    public function del(){
        $id=$this->request->input('div_id');
        $quizzer=Divination::where(['id'=>$id,'uid'=>$this->uid()])->delete();
        return Response::success($quizzer);

    }


}
